package com.ml.mall.aspect;

import com.ml.mall.annotations.RequiresRoutings;
import com.ml.mall.entity.sys.SysRouting;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.sys.SysRoutingService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @description 路由检测切面
 * @author yx
 * @date 2021/9/15
 * @version 1.0
*/
@Component
@Aspect
public class RequiresRoutingAspect {

    @Autowired
    private SysRoutingService sysRoutingService;

    @Pointcut("execution(* com.ml.mall.api..*.*(..)) && @annotation(com.ml.mall.annotations.RequiresRoutings)")
    public void requiresRoutingPointcut(){}

    @Before(value = "requiresRoutingPointcut() && @annotation(requiresRoutings)")
    public void checkRouting(JoinPoint joinPoint, RequiresRoutings requiresRoutings){
        //获取用户公司的配套路由信息
        SysUser currentUser = JwtUtil.getCurrentUser();
        List<String> userRoutingPermissions = sysRoutingService.getRoutingPermissionsByCompanyId(currentUser.getCompanyId());
        //访问接口所需路由权限
        List<String> requiresRoutingPermissions = Arrays.asList(requiresRoutings.value());
        //用户的配套路由不满足访问的配套路由时抛出异常
        if(!userRoutingPermissions.containsAll(requiresRoutingPermissions)){
            throw new BizException(CommonEnum.NO_SUBSCRIPTION);
        }
    }
}
